import cropperModal from "@/components/cropper/index.vue";
import { fileBase64 } from "@/util/util";
import { platformgoodscategorytree, addObj, putObj } from '@/api/shop/goods/category.js'
import { upLoad } from '@/api/shop/upLoad.js'

export default {
    components: {
        cropperModal
    },
    data() {
        var valiImg = (rule, value, callback) => { // 图片验证
            if (!this.hasFmt) {
                callback(new Error('请上传类目图标'));
            } else {
                callback();
            }
        }
        return {
            dialogVisible: false,
            dialogVisibleTile: "",
            loading: false,
            labelWidth: "120px",
            rules: {
                categoryName: [
                    { required: true, message: '请输入类目名称', trigger: 'blur' }
                ],
                operatorId: [
                    { required: true, message: '请选择上级类目' }
                ],
                lmtb: [
                    {
                        required: true, validator: valiImg, trigger: 'change'
                    }
                ]

            },
            ruleForm: {

            },
            form: {},
            disabled: false,
            sjlmList: [],//上级类目

            imageUrl: "",
            loading: false, //上传
            optionsData: {
                title: "商品图片", //弹框表头
                img: "", //裁切图片地址
                autoCrop: true, //是否默认生成截图框
                autoCropWidth: 326, //默认生成截图框宽度
                autoCropHeight: 412, //默认生成截图框高度
                fixedBox: false, //固定截图框大小 不允许改变
                thumbnailName: "衣家生活"
            },
            number: 0,
            fileList: [],
            dialogImageUrl: "", //放大图片
            dialogVisibleImg: false,
            businessType: '',
            imgUrlList: []
        };
    },
    methods: {
        getCategory(row) {
            this.ruleForm = {}
            this.fileList = []
            this.imgUrlList = []
            platformgoodscategorytree({ businessType: this.businessType }).then(val => {
                let data = val.data.data
                console.log(data)
                this.sjlmList = data.map(item => {
                    return {
                        label: item.categoryName,
                        value: item.categoryId,
                    }
                })
            })
            if (row.categoryName) {   //编辑回显
                let obj = { ...row }
                console.log(obj)
                if (obj.pid == '0') {
                    obj.pid = ''
                }
                if (obj.categoryIcon) {   //图片回显
                    let pic = []
                    if (obj.categoryIcon.indexOf(',') > -1) {
                        pic = obj.categoryIcon.split(',')
                        pic.forEach(item => {
                            this.fileList.push({ url: process.url + item, name: '商品图片' })
                            this.imgUrlList.push({ url: item, name: '商品图片' })
                        })
                    } else {
                        this.fileList.push({ url: process.url + obj.categoryIcon, name: '商品图片' })
                        this.imgUrlList.push({ url: obj.categoryIcon, name: '商品图片' })
                    }
                }

                this.ruleForm = obj
                console.log(this.ruleForm)
            }
        },
        handleClose() {
            this.dialogVisible = false
            this.ruleForm = {}
            this.fileList = []
            this.imgUrlList = []
        },
        handleSure() {
            let obj = {}
            const urlList = [...this.imgUrlList]
            if (urlList.length) {  //图片处理
                const imgList = []
                urlList.forEach(item => {
                    if (item.url.indexOf(process.url) > -1) {  //截取路径
                        item.url = item.url.replace(process.url, '')
                    }
                    imgList.push(item.url)
                })
                this.ruleForm.categoryIcon = imgList.join(',')
            }
            Object.assign(obj, this.ruleForm, { businessType: this.businessType, showFlag: "01", deptId: this.$store.getters.userInfo.deptId, tenantId: this.$store.getters.userInfo.tenantId, })

            // console.log(obj)
            // return
            this.$refs['ruleForm'].validate((valid) => {
                if (valid) {
                    // if (this.ruleForm.categoryIcon) {
                    //     addObj(obj).then(() => {
                    //         this.$message.success('添加成功')
                    //         this.handleClose()
                    //         this.$parent.$parent.getList()
                    //     })
                    // } else {
                    //     this.$message.warning('请上传类目图标')
                    // }
                    addObj(obj).then(() => {
                        this.$message.success('添加成功')
                        this.handleClose()
                        this.$parent.$parent.getList()
                    })
                } else {
                    return false;
                }
            });
        },
        handleUpdata() {
            let obj = {}
            let urlList = [...this.imgUrlList]
            if (urlList.length) {  //图片处理
                let imgList = []
                urlList.forEach(item => {
                    if (item.url.indexOf(process.url) > -1) {  //截取路径
                        item.url = item.url.replace(process.url, '')
                    }
                    imgList.push(item.url)
                })
                this.ruleForm.categoryIcon = imgList.join(',')
            }
            Object.assign(obj, this.ruleForm, { businessType: this.businessType, deptId: this.$store.getters.userInfo.deptId, tenantId: this.$store.getters.userInfo.tenantId })
            this.$refs['ruleForm'].validate((valid) => {
                if (valid) {
                    if (!obj.pid) {
                        obj.pid = '0'
                        obj.showFlag = ''
                    }
                    // if (this.ruleForm.categoryIcon) {
                    //     putObj(obj).then(val => {
                    //         this.$message.success('修改成功')
                    //         this.$parent.$parent.getList({}, 1, this.businessType)
                    //         this.dialogVisible = false
                    //     })
                    // } else {
                    //     this.$message.warning('请上传类目图标')
                    // }
                    putObj(obj).then(val => {
                        this.$message.success('修改成功')
                        this.$parent.$parent.getList({}, 1, this.businessType)
                        this.dialogVisible = false
                    })
                } else {
                    return false;
                }
            });
        },
        handleChange(file) {
            //上传触发
            // console.log(file)
            let { options } = this;
            // console.log(file)
            // fileBase64(file.file.originFileObj).then(result => {
            let target = Object.assign({}, options, {
                img: file.url,
                files: file
            });
            this.$refs["cropperModal"].edit(target);
            // })
        },
        beforeUpload(file) {
            const isJpgOrPng =
                file.type === "image/jpeg" || file.type === "image/png";
            if (!isJpgOrPng) {
                this.$message.error("图片格式不支持！");
            }
            const isLt1M = file.size / 1024 / 1024 < 1;
            if (!isLt1M) {
                this.$message.error("图片大小限制在1MB内!");
            }
            return isJpgOrPng && isLt1M;
        },
        handlePictureCardPreview(file) {
            this.dialogVisible = true;
            this.dialogImageUrl = file.url
        },
        delUplod(file) {
            this.hasFmt = false   //图片验证开启
            const index = this.fileList.indexOf(file);
            const newFileList = this.fileList.slice();
            newFileList.splice(index, 1);
            this.fileList = newFileList;
            this.imgUrlList.splice(index, 1)
        },
        handleCropperSuccess(data) {
            //图片裁切完成保存
            console.log(data)
            upLoad(data).then(res => {
                this.imgUrlList.push(res.data.data)
                this.fileList.push({
                    uid: this.number++,
                    name: 'image.png',
                    status: 'done',
                    url: URL.createObjectURL(data)
                })
                this.$message.success('上传成功！')
            }).catch(() => {
                this.$message.warning('上传失败，请重新上传！')
            })
            this.$refs.lmtbUpload.clearValidate(); // 关闭图片校验
            this.hasFmt = true   //图片验证开启
        },
        lmmcChange() {               //类目名称查重

        }
    }
};